<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="电梯注册代码" prop="elevatorId">
        <el-select v-model="form.elevatorId" filterable placeholder="请选择电梯注册代码" style="width: 300px">
          <el-option
            v-for="item in elevatorList"
            :key="item.elevatorId"
            :label="item.registrationCode+' / '+ item.factoryNumber+'/ '+ item.ytPlaceInfo.placeName"
            :value="item.elevatorId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="维护日期" prop="maintenanceDate">
        <el-date-picker clearable
                        v-model="queryParams.maintenanceDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择维护日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="费用" prop="cost">
        <el-input
          v-model="queryParams.cost"
          placeholder="请输入费用"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排序字段" prop="sortOrder">
        <el-input
          v-model="queryParams.sortOrder"
          placeholder="请输入排序字段"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:record:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:record:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:record:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:record:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="电梯注册代码/出厂编号" align="center" prop="elevatorId" width="200">
        <template slot-scope="scope">
          <span v-for="item in elevatorList" v-if="scope.row.elevatorId === item.elevatorId">{{ item.registrationCode }} / {{item.factoryNumber}}</span>
        </template>
      </el-table-column>
      <el-table-column label="维护日期" align="center" prop="maintenanceDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.maintenanceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维护类型" align="center" prop="maintenanceType" />
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="费用" align="center" prop="cost" />
      <el-table-column label="检查相册" align="center" prop="checkImages" />
      <el-table-column label="维修后相册" align="center" prop="maintenanceImages" />
      <el-table-column label="更换部件相册" align="center" prop="replacedPartsImages" />
      <el-table-column label="排序字段" align="center" prop="sortOrder" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleInfo(scope.row)"
            v-hasPermi="['business:record:info']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:record:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:record:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改维修记录，用于存储电梯的维护记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电梯注册代码" prop="elevatorId">
              <el-select v-model="form.elevatorId" filterable placeholder="请选择电梯注册代码" style="width: 300px">
                <el-option
                  v-for="item in elevatorList"
                  :key="item.elevatorId"
                  :label="item.registrationCode+' / '+ item.factoryNumber+'/ '+ item.ytPlaceInfo.placeName"
                  :value="item.elevatorId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维护日期" prop="maintenanceDate">
              <el-date-picker clearable
                              v-model="form.maintenanceDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择维护日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="费用" prop="cost">
              <el-input-number v-model="form.cost" placeholder="请输入费用" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维护类型" prop="maintenanceType">
              <el-select v-model="form.maintenanceType" placeholder="请选择维护类型">
                <el-option
                  v-for="dict in dict.type.bus_maintenance_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序字段" prop="sortOrder">
              <el-input-number :min="0" v-model="form.sortOrder" placeholder="请输入排序字段" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检查相册" prop="checkImages">
              <image-upload v-model="form.checkImages"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维修后相册" prop="maintenanceImages">
              <image-upload v-model="form.maintenanceImages"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="更换部件相册" prop="replacedPartsImages">
              <image-upload v-model="form.replacedPartsImages"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddYtAssignedTask">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteYtAssignedTask">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="ytAssignedTaskList" :row-class-name="rowYtAssignedTaskIndex" @selection-change="handleYtAssignedTaskSelectionChange" ref="ytAssignedTask">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="维修负责人" prop="userId" >
            <template slot-scope="scope">
              <el-select v-model="scope.row.userId" filterable placeholder="请选择负责师傅" style="width: 300px">
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.nickName+'/'+item.phonenumber"
                  :value="item.userId">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="指派日期" prop="assignedDate" >
            <template slot-scope="scope">
              <el-date-picker clearable v-model="scope.row.assignedDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择指派日期" />
            </template>
          </el-table-column>
          <el-table-column label="完成日期" prop="completionDate" >
            <template slot-scope="scope">
              <el-date-picker clearable v-model="scope.row.completionDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择完成日期" />
            </template>
          </el-table-column>
          <el-table-column label="指派状态" prop="status" >
            <template slot-scope="scope">
              <el-select v-model="scope.row.status" placeholder="请选择指派状态">
                <el-option v-for="dict in dict.type.bus_task_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="排序字段" prop="sortOrder" width="250">
            <template slot-scope="scope">
              <el-input-number :min="0" v-model="scope.row.sortOrder" placeholder="请输入排序字段" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from "@/api/business/record";
import { listElevator } from "@/api/business/elevator";
import { listUser } from "@/api/system/user";


export default {
  name: "Record",
  dicts: ['bus_maintenance_type', 'bus_task_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedYtAssignedTask: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 维修记录表格数据
      recordList: [],
      // 电梯信息
      elevatorList: [],
      ytAssignedTaskList:[],
      userList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      openInfo: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        elevatorId: null,
        maintenanceDate: null,
        maintenanceType: null,
        description: null,
        cost: null,
        checkImages: null,
        maintenanceImages: null,
        replacedPartsImages: null,
        sortOrder: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        elevatorId: [
          { required: true, message: "电梯注册码不能为空", trigger: "blur" }
        ],
        maintenanceDate: [
          { required: true, message: "维护日期不能为空", trigger: "blur" }
        ],
        maintenanceType: [
          { required: true, message: "维护类型不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getElevatorList();
    this.getUserList();
    this.getList();
  },
  methods: {
    /** 查询用户列表 */
    getUserList() {
      this.loading = true;
      listUser({pageSize: 10000,userType:'01'}).then(response => {
          this.userList = response.rows;
        }
      );
    },
    /** 查询电梯信息 */
    getElevatorList() {
      this.loading = true;
      listElevator({pageSize: 10000}).then(response => {
        this.elevatorList = response.rows;
        console.log("电梯信息",this.elevatorList)
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询维修记录列表 */
    getList() {
      this.loading = true;
      listRecord(this.queryParams).then(response => {
        this.recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openInfo = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        recordId: null,
        elevatorId: null,
        maintenanceDate: null,
        maintenanceType: '日常巡检',
        description: null,
        cost: null,
        checkImages: null,
        maintenanceImages: null,
        replacedPartsImages: null,
        sortOrder: 0,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        delFlag: null
      };
      this.ytAssignedTaskList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recordId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加维修记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const recordId = row.recordId || this.ids
      getRecord(recordId).then(response => {
        this.form = response.data;
        this.ytAssignedTaskList = response.data.ytAssignedTaskList;
        this.open = true;
        this.title = "修改维修记录";
      });
    },
    /** 详情按钮操作 */
    handleInfo(row) {
      this.reset();
      const recordId = row.recordId || this.ids
      getRecord(recordId).then(response => {
        this.form = response.data;
        this.openInfo = true;
        this.title = "维修记录详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.ytAssignedTaskList = this.ytAssignedTaskList;
          if (this.form.recordId != null) {
            updateRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recordIds = row.recordId || this.ids;
      this.$modal.confirm('是否确认删除维修记录编号为"' + recordIds + '"的数据项？').then(function() {
        return delRecord(recordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 指派维修任务，用于记录维修任务的指派和完成情况序号 */
    rowYtAssignedTaskIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 指派维修任务，用于记录维修任务的指派和完成情况添加按钮操作 */
    handleAddYtAssignedTask() {
      let obj = {};
      obj.userId = "";
      obj.assignedDate = "";
      obj.completionDate = "";
      obj.feedback = "";
      obj.status = "";
      obj.images = "";
      obj.sortOrder = "";
      obj.remark = "";
      this.ytAssignedTaskList.push(obj);
    },
    /** 指派维修任务，用于记录维修任务的指派和完成情况删除按钮操作 */
    handleDeleteYtAssignedTask() {
      if (this.checkedYtAssignedTask.length == 0) {
        this.$modal.msgError("请先选择要删除的指派维修任务，用于记录维修任务的指派和完成情况数据");
      } else {
        const ytAssignedTaskList = this.ytAssignedTaskList;
        const checkedYtAssignedTask = this.checkedYtAssignedTask;
        this.ytAssignedTaskList = ytAssignedTaskList.filter(function(item) {
          return checkedYtAssignedTask.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleYtAssignedTaskSelectionChange(selection) {
      this.checkedYtAssignedTask = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/record/export', {
        ...this.queryParams
      }, `record_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
